<template>
  <div class="ant-layout-content basic-layout">
    <router-view v-slot="{ Component, route }">
      <a-spin class="page-loading-spinner" :spinning="globalLoadingRef">
        <div>
          <!-- 1. 在Route里设置meta.keepAlive属性，决定是否需要keep-alive -->
          <!-- 2. 设置key是为了解决TypeError: parentComponent.ctx.deactivate is not a function 问题，
                        参考：https://www.gitmemory.com/issue/vuejs/vue-next/1513/653929143
                        解决方案: Make sure to never use NaN as a key. -->
          <keep-alive>
            <component v-if="route.meta.keepAlive" :key="route.name" :is="Component" />
          </keep-alive>
          <component v-if="!route.meta.keepAlive" :is="Component" />
        </div>
      </a-spin>
    </router-view>
  </div>
</template>
<script lang="ts">
import { CommonStore } from "@/store";
import { watch, ref } from "vue";
import { getMenuData, clearMenuItem } from "@ant-design-vue/pro-layout";
import { useRouter } from "vue-router";
export default {
  neme: "empty-layout",
  setup(props) {
    const commonStore = CommonStore();
    const globalLoadingRef = ref(false);
    const globalLoadingTimerRef = ref<any>(null);
    const keepAlivePages = ref("");
    const router = useRouter();
    const { menuData } = getMenuData(clearMenuItem(router.getRoutes()));
    menuData.forEach((item: any) => {
      if (item.meta.keepAlive) {
        keepAlivePages.value += item.name + ",";
      }
    });

    watch(commonStore.$state.loadingIdList, (newValue) => {
      /**
       * 全局加载状态处理
       */
      if (!globalLoadingTimerRef.value)
        globalLoadingTimerRef.value = setTimeout(() => {
          globalLoadingRef.value = !!newValue.length;
        }, 200);
      if (!newValue.length) {
        if (globalLoadingTimerRef.value) {
          clearTimeout(globalLoadingTimerRef.value);
          globalLoadingTimerRef.value = null;
        }
        globalLoadingRef.value = !!newValue.length;
      }
    });

    return {
      globalLoadingRef,
      keepAlivePages,
    };
  },
};
</script>
<style scoped>
.ant-layout-content {
  background-color: #f1f4f5;
  height: 100vh;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
